package org.web2024.fliter;

import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.web2024.dao.User;
import org.web2024.dao.UserdetailsImp;
import org.web2024.mapper.UserMapper;
import org.web2024.utils.jwtUtil;

import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request,  HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {//如果没有token就放行
            filterChain.doFilter(request, response);
            return;
        }
        String UserNo;
        System.out.println(token);
        try{
            Claims claims = jwtUtil.checkJWT(token);
            UserNo = (String) claims.get("no");
        }catch (Exception e){
            throw new RuntimeException("token失效");
        }

        //获取用户信息，根据id发送token
        UserdetailsImp userdetailsImp =  (UserdetailsImp) redisTemplate.opsForValue().get("login:" + UserNo);
        if(userdetailsImp==null){
            filterChain.doFilter(request, response);
            return;
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userdetailsImp, null, userdetailsImp.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
